<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <!-- 导入页面的基本样式 -->
    <link rel="stylesheet" href="./css/search.css" />
    <!-- 导入 jQuery -->
    <script src="./lib/jquery.js"></script>
    <script src="./lib/template-web.js"></script>
  </head>
  <body>
    <div class="container">
      <!-- Logo -->
      <img src="./images/taobao_logo.png" alt="" class="logo" />

      <div class="box">
        <!-- tab 栏 -->
        <div class="tabs">
          <div class="tab-active">宝贝</div>
          <div>店铺</div>
        </div>
        <!-- 搜索区域（搜索框和搜索按钮） -->
        <div class="search-box">
          <input type="text" class="ipt" placeholder="请输入要搜索的内容" /><button class="btnSearch">
            搜索
          </button>
        </div>
        <!-- 搜索列表 -->
        <div id="suggest-list"></div>
      </div>
    </div>
    <script type="text/html" id="suggest-box">
      {{each result}}
          <div class="suggest-items">{{$value[0]}}</div>
      {{/each}}
    </script>
    <script>
      $(function(){
        //全局缓存对象
        var cacheObj = {};
        //防抖
        var timer;
        //防抖函数
        function debouncesearch(kw){
          timer = setTimeout(() => {
            getSuggestList(kw);
          }, 300);
        }
        function getSuggestList(kw) {
          $.ajax({
            url:'https://suggest.taobao.com/sug?q='+kw,
            dataType:'jsonp',
            success: function(res) {
              console.log(res);
              renderSuggestList(res);
            }
          })
        }
        function renderSuggestList(res) {
          if (res.result.length <= 0) {
            return $('#suggest-list').empty().hide();
          }
            var htmlStr = template('suggest-box',res);
            $('#suggest-list').html(htmlStr).show();
            var k = $('.ipt').val().trim();
            cacheObj[k] = res;
        }
        $('.ipt').on('keyup',function(){
          
          clearTimeout(timer);
          var keydata = $(this).val().trim();
          if (cacheObj[keydata]) {
            return renderSuggestList(cacheObj[keydata]);
          }
          if (keydata.length <= 0) {
            $('#suggest-list').empty().hide();
          }
          debouncesearch(keydata);
        })
      })
    </script>
  </body>
</html>
